package com.diandiansong.app.ui.index;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.diandiansong.app.App;
import com.diandiansong.app.R;
import com.diandiansong.app.entity.BuyNowObj;
import com.diandiansong.app.entity.ComodityViewInfo;
import com.diandiansong.app.ui.base.BaseAct;
import com.diandiansong.app.ui.cart.OrderCheck;
import com.diandiansong.app.utils.A;
import com.diandiansong.app.utils.Api;
import com.diandiansong.app.widgets.AddAndMinusViewInItem;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import diandiansong.library.utils.BaseEntity;
import diandiansong.library.utils.CCallBack;
import diandiansong.library.utils.ImgLoader;
import diandiansong.library.widgets.FlowLayout;

/**
 * 商品详情
 */
public class GoodDetail extends BaseAct {

    static String mId;
    static int mCount;

    @BindView(R.id.banner)
    Banner mBanner;
    @BindView(R.id.tv_goods_title)
    TextView mTvGoodsTitle;
    @BindView(R.id.tv_goods_subtitle)
    TextView mTvGoodsSubtitle;
    @BindView(R.id.tv_goods_subtitle_2)
    TextView mTvGoodsSubtitle2;
    @BindView(R.id.tv_price)
    TextView mTvPrice;
    @BindView(R.id.tv_unit)
    TextView mTvUnit;
    @BindView(R.id.tv_price_kill_old)
    TextView mTvKillPriceOld;
    @BindView(R.id.add_minus)
    AddAndMinusViewInItem mAddMinus;
    @BindView(R.id.web_view)
    WebView mWebView;
    @BindView(R.id.tv_total_price)
    TextView mTvTotalPrice;
    @BindView(R.id.tv_count)
    TextView mTvCount;
    @BindView(R.id.do_add_cart)
    TextView mDoAddCart;
    @BindView(R.id.do_pay)
    TextView mDoPay;
    @BindView(R.id.sku)
    FlowLayout mSkusView;
    View[] mSkuViews;
    @BindView(R.id.do_favorite)
    View mDoFavorite;
    @BindView(R.id.tb_favorite)
    ToggleButton mTbFavorite;

    @BindView(R.id.ll_gift)
    View mViewGift;
    @BindView(R.id.tv_gift)
    TextView mTvGift;

    public static void start(Context context, String id) {
        mId = id;
        mCount = 1;
        Intent starter = new Intent(context, GoodDetail.class);
        context.startActivity(starter);
    }

    ComodityViewInfo.Data mGood;
    ComodityViewInfo.Data.Sku mSku;
    boolean mFromKill;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        hideTitle();

        addContentView(R.layout.goods_detail);

        mAddMinus.setOnChangeListener(null);

        onLoading();
        A.commodityView(mId, new CCallBack<ComodityViewInfo>() {
            @Override
            public void onSuccess(ComodityViewInfo o) throws Exception {
                onLoaded();
                final ComodityViewInfo.Data data = o.getData();
                mGood = data;

                if (data == null) {
                    toast("商品不存在");
                    return;
                }

                mFromKill = data.getKillPriceF() != 0f;

                mTvKillPriceOld.setVisibility(mFromKill ? View.VISIBLE : View.GONE);

                if (mGood.isTourist()) {
                    mDoPay.setBackgroundColor(Color.parseColor("#cccccc"));
                    mDoAddCart.setBackgroundColor(Color.parseColor("#cccccc"));
                }

                if (mGood.getGift() != null && !mGood.getGift().isEmpty()) {
                    mViewGift.setVisibility(View.VISIBLE);
                    mTvGift.setText(mGood.getGift());

                } else {
                    mViewGift.setVisibility(View.GONE);
                }

                mWebView.loadUrl(Api.URL + "/app/commodity_view?id=" + mId);

                mAddMinus.setNum(mCount);

                if (mGood.isTourist()) {
//                    mTvTotalPrice.setText("合计：￥ --");
                    mTvTotalPrice.setText("合计：");

                } else {
                    mTvTotalPrice.setText("合计：￥" + App.readable(mFromKill ? data.getKillPriceF() * mCount : (data.getPriceF() * mCount)));
                }
                mTvCount.setText("数量：" + mCount);

                mAddMinus.setOnChangeListener(new AddAndMinusViewInItem.OnChangeListener() {
                    @Override
                    public void onChange(int num) {
                        mTvCount.setText("数量：" + num);

                        if (mGood.isTourist()) {
                            return;
                        }

                        mCount = num;

                        //根据规格算价格
                        if (mSku == null) {
                            mTvTotalPrice.setText("合计：￥" + App.readable(mFromKill ? data.getKillPriceF() * mCount : (data.getPriceF() * mCount)));


                        } else {
                            mTvTotalPrice.setText("合计：￥" + App.readable(mFromKill ? mSku.getKillPriceF() * mCount : (mSku.getPriceF() * mCount)));
                        }
                    }
                });

                mBanner.setImageLoader(new ImageLoader() {
                    @Override
                    public void displayImage(Context context, Object path, ImageView imageView) {
                        ImgLoader.display(imageView, (String) path);
                    }
                });
                mBanner.setImages(data.getImgs());
                mBanner.setOnBannerListener(new OnBannerListener() {
                    @Override
                    public void OnBannerClick(int position) {

                    }
                });
                mBanner.isAutoPlay(false);
                mBanner.start();
                setText(mTvGoodsTitle, data.getCommodityName());
                setText(mTvGoodsSubtitle, data.getCommoditySubtitle());
                setText(mTvPrice, mFromKill ? data.getKillPrice() : data.getPrice());
                setText(mTvKillPriceOld, data.getPrice() + "/" + data.getUnit());
                mTvKillPriceOld.setPaintFlags(mTvKillPriceOld.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                setText(mTvUnit, "/" + data.getUnit());

                mTbFavorite.setChecked(data.isCollection());

                //显示规格
                List<ComodityViewInfo.Data.Sku> skus = data.getSku();
                if (skus != null && skus.size() > 0) {
                    mSkuViews = new View[skus.size()];
                    for (int i = 0; i < skus.size(); i++) {
                        final ComodityViewInfo.Data.Sku sku = skus.get(i);

                        View itemView = LayoutInflater.from(getActivity()).inflate(R.layout.good_detail_sku_item, null);
                        itemView.setLayoutParams(new ViewGroup.MarginLayoutParams(new ViewGroup.LayoutParams(
                                ViewGroup.LayoutParams.WRAP_CONTENT,
                                ViewGroup.LayoutParams.WRAP_CONTENT
                        )));
                        TextView tvName = itemView.findViewById(diandiansong.library.R.id.tv_name);
                        tvName.setText(sku.getSpecInfo());
                        itemView.setTag(sku);
                        itemView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (mGood.isTourist()) {
                                    return;
                                }
                                for (View skuView : mSkuViews) {
                                    skuView.findViewById(R.id.tv_name).setActivated(false);
                                }
                                v.findViewById(R.id.tv_name).setActivated(true);
                                mSku = (ComodityViewInfo.Data.Sku) v.getTag();
                                mTvPrice.setText(mFromKill ? sku.getKillPrice() : sku.getPrice());
                                mCount = mAddMinus.getNum();
                                mTvTotalPrice.setText("合计：￥" + App.readable(mFromKill ? mSku.getKillPriceF() * mCount : (mSku.getPriceF() * mCount)));

                                setSubTitle2();
                            }
                        });
                        mSkusView.addView(itemView);
                        mSkuViews[i] = itemView;
                    }
                    mSku = skus.get(0);
                    mSkuViews[0].findViewById(R.id.tv_name).setActivated(true);
                    //第一个规格的限购起购

                    setSubTitle2();


                } else {
                    //没有规格
                    if (data.isPurchaseTypesLimit()) {
                        //限购
                        if (data.getPurchase() == 0) {
                            mTvGoodsSubtitle2.setText("");
                            mAddMinus.setMax(Integer.MAX_VALUE);
                        } else {
                            mAddMinus.setMax(data.getPurchase());
                            mTvGoodsSubtitle2.setText(data.getPurchaseName());
                        }

                    } else {
                        //起购
                        if (data.getPurchase() == 0) {
                            mTvGoodsSubtitle2.setText("");

                        } else {
                            mTvGoodsSubtitle2.setText(data.getPurchaseName());
                            mAddMinus.setMin(data.getPurchase());
                        }
                    }
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                onLoaded();
                toast(msg);
            }
        });
    }

    void setSubTitle2() {
        {
            if (mGood.isPurchaseTypesLimit()) {
                //限购
                if (mSku.getPurchase() == 0) {
                    mTvGoodsSubtitle2.setText("");
                    mAddMinus.setMax(Integer.MAX_VALUE);
                } else {
                    mAddMinus.setMax(mSku.getPurchase());
                    mTvGoodsSubtitle2.setText(mSku.getPurchaseName());
                }

            } else {
                //起购
                if (mSku.getPurchase() == 0) {
                    mTvGoodsSubtitle2.setText("");
                    mAddMinus.setMin(1);

                } else {
                    mTvGoodsSubtitle2.setText(mSku.getPurchaseName());
                    mAddMinus.setMin(mSku.getPurchase());
                }
            }
        }
    }

    @OnClick(R.id.iv_back)
    public void onMIvBackClicked() {
        finish();
    }

    @OnClick(R.id.do_add_cart)
    public void onMDoAddCartClicked() {
        if (mGood.isTourist()) {
            toast("您当前为游客，不能加入购物车");
            return;
        }
        if (mGood == null) {
            return;
        }
        if (mAddMinus.getNum() < 1) {
            toast("请选择购买数量");
            return;
        }
        if (mSkuViews != null && mSkuViews.length > 0 && mSku == null) {
            toast("请选择规格");
            return;
        }
        String sku_id = "0";
        if (mSku != null) {
            sku_id = mSku.getProductId();
        }
        A.cartStore(mGood.getCommodityId(), mAddMinus.getNum(), sku_id, new CCallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity o) throws Exception {
                toast("已加入购物车");
            }

            @Override
            public void onFailure(int code, String msg) {
                toast(msg);
            }
        });
    }

    @OnClick(R.id.do_pay)
    public void onMDoPayClicked() {
        if (mGood.isTourist()) {
            toast("您当前为游客，不能购买");
            return;
        }
        if (mGood == null) {
            return;
        }
        if (mAddMinus.getNum() < 1) {
            toast("请选择购买数量");
            return;
        }
        if (mSkuViews != null && mSkuViews.length > 0 && mSku == null) {
            toast("请选择规格");
            return;
        }
        String sku_id = "0";
        if (mSku != null) {
            sku_id = mSku.getProductId();
        }
        BuyNowObj buyNowObj = new BuyNowObj(mGood.getCommodityId(), sku_id, mAddMinus.getNum(), mGood);
        OrderCheck.start(getActivity(), buyNowObj);
    }

    @OnClick(R.id.do_favorite)
    public void onFavoriteViewClicked() {
        if (mGood.isTourist()) {
            toast("您当前为游客，不能收藏");
            return;
        }
        final boolean checked = mTbFavorite.isChecked();
        A.commodityCollection(mGood.getCommodityId(), new CCallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity baseEntity) throws Exception {
                toast(checked ? "已取消收藏" : "已收藏");
            }

            @Override
            public void onFailure(int code, String msg) {
                toast(msg);
            }
        });
        mTbFavorite.setChecked(!checked);
    }
}
